package com.tjetc.dao.impl;

import com.tjetc.dao.RecordDao;
import com.tjetc.domain.Record;
import com.tjetc.utils.Db;
import com.tjetc.utils.PageInfo;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class RecordDaoImpl implements RecordDao {
    @Override
    public int add(Record record) throws SQLException {
        return Db.runner0().update("insert into record(uid, did, description, result, isLive) values (?,?,?,?,?)",
                record.getUid(),record.getDid(),record.getDescription(),record.getResult(),record.getIsLive());
    }

    @Override
    public int getMaxId() throws SQLException {
        return Db.runner0().query("select max(id) from record",new ScalarHandler<>());
    }

    @Override
    public List<Record> listMyRecord(int uid) throws SQLException {
        return Db.runner0().query("select * from record where uid = ?",new BeanListHandler<>(Record.class),uid);
    }

    @Override
    public Record getById(int id) throws SQLException {
        return Db.runner0().query("select * from record where id = ?",new BeanHandler<>(Record.class),id);
    }


    @Override
    public int getCount(int did) throws SQLException {
        return ((Long)Db.runner0().query("select count(id) from record where did = ?",
                new ScalarHandler<>(),did)).intValue();
    }

    @Override
    public List<Record> list(PageInfo<Record> pageInfo, int did) throws SQLException {
        return Db.runner0().query("select * from record where did = ? limit ?,? ",
                new BeanListHandler<>(Record.class),did,
                pageInfo.getStartRecord(),pageInfo.getPageSize());
    }

    @Override
    public void out(int id) throws SQLException {
        Db.runner().update(Db.getConnection(),"update record set isLive = 2 where id = ?",id);
    }

}
